<?php
/**
 * 知识模型
 * 
 * @package ews
 * @ews Enterprise WorkShop
 * @version 1.0 alpha
 * @since 2011-06-11
 * @author chenyan
 */

class knowledgeModel extends model
{
	/**************************************************************************
	 * 1 知识部分返回数结构
	 *  knowledge_id		int			知识ID
	 *  user_id					int			知识发布者ID
	 *  subject					string		标题
	 *  message					string		最后发布条目内容，文字需要被截取到80个字
	 *  flag_item_add			int			0：所有人可添加	1：指定小组可以添加	2：只有主题创建者可以添加
	 *  flag_item_add_group_id	int			如果是绑定到小组，这里是小组的ID
	 *  flag_item_view			int			0：所有人可浏览和下载		1：指定小组可以浏览和下载		2：只有主题创建者可以浏览和下载
	 *  flag_item_view_group_id	int			如果是绑定到小组，这里是小组的ID
	 *  main_tag				string		主题归档		（人力/财务/通用）
	 *  item_count				int			条目数量
	 *  mktime					int			发布时间戳
	 *  atta_count				int			其item中的附件（item类型为file的）总数
	 *  
	 *  username（user表）		string		用户名（若返回数组中指明包含用户名信息，此字段有效）
	 * 
	 * 
	 * 2 知识条目返回数组结构
	 *  knowledge_item_id		int			条目ID
	 *  knowledge_id			int			所属知识ID
	 *  user_id					int			发布者ID
	 *  type					int			数据类型  0:message  1:file
	 *  data					string		内容		文件：序列化的信息文字：直接是文字
	 *  											文件序列化格式：array(filename,size,type,url);对该数组序列化
	 *  mktime					int			发布时间戳
	 * 
	 **************************************************************************/
	
	
	
	/****************************knowledge 部分*********************************/
	
	
	/**
	 * 增加一条知识
	 * @param int $user_id			知识发布者ID
	 * @param string $subject		标题
	 * @param string $message		最后发布条目内容，文字需要被截取到80个字
	 * @param int $flag_item_add				0：所有人可添加	1：指定小组可以添加	2：只有主题创建者可以添加
	 * @param int $flag_item_add_group_id		如果是绑定到小组，这里是小组的ID
	 * @param int $flag_item_view				0：所有人可浏览和下载		1：指定小组可以浏览和下载		2：只有主题创建者可以浏览和下载
	 * @param int $flag_item_view_group_id		如果是绑定到小组，这里是小组的ID	
	 * @param string $main_tag					主题归档（人力/财务/通用）
	 * @return int	新插入知识ID
	 */
	public function add($user_id,$subject,$message,$flag_item_add,$flag_item_add_group_id,
						$flag_item_view,$flag_item_view_group_id,$main_tag){
		$data = array('subject' => $subject,'item_count' => 0,'user_id' => $user_id,'message' => $message,
				'flag_item_add'=>$flag_item_add,'flag_item_add_group_id'=>$flag_item_add_group_id,'flag_item_view'=>$flag_item_view,
				'flag_item_view_group_id'=>$flag_item_view_group_id,'main_tag'=>$main_tag,'mktime'=>time(),'atta_count'=>0);
		$id = DB::insert('knowledge', $data);
		return $id;
	}
	/**
	 * 根据ID删除一条知识
	 * @param int $knowledge_id		知识ID
	 * @return int	1：成功 0：失败
	 */
	public function delete($knowledge_id){
		$condition = "knowledge_id=$knowledge_id";
		//先删除item表相应数据
		$row1 = DB::delete('knowledge_item',$condition);
		if($row1>=0) $row2 = DB::delete('knowledge',$condition);
		if($row2>0) return 1;
		else return 0;
	}
	
	/**
	 * 根据ID修改一条知识
	 * @param int $knowledge_id		知识ID
	 * @param int $user_id			知识发布者ID
	 * @param string $subject		标题
	 * @param string $message		最后发布条目内容
	 * @param int $flag_item_add				0：所有人可添加	1：指定小组可以添加	2：只有主题创建者可以添加
	 * @param int $flag_item_add_group_id		如果是绑定到小组，这里是小组的ID
	 * @param int $flag_item_view				0：所有人可浏览和下载		1：指定小组可以浏览和下载		2：只有主题创建者可以浏览和下载
	 * @param int $flag_item_view_group_id		如果是绑定到小组，这里是小组的ID
	 * @param string $main_tag					主题归档	（人力/财务/通用）
	 * @return int	1：成功 0：失败
	 */
	public function modify($knowledge_id,$user_id,$subject,$message,$flag_item_add,$flag_item_add_group_id,
						$flag_item_view,$flag_item_view_group_id,$main_tag){
		$data = array('subject' => $subject,'user_id' => $user_id,'message' => $message,
			'flag_item_add'=>$flag_item_add,'flag_item_add_group_id'=>$flag_item_add_group_id,'flag_item_view'=>$flag_item_view,
			'flag_item_view_group_id'=>$flag_item_view_group_id,'main_tag'=>$main_tag);
		$condition = "knowledge_id=$knowledge_id";
		$row = DB::update('knowledge',$data,$condition);
		if($row>0) return 1;
		else return 0;
	}
	/*
	public function set_item_count($knowledge_id,$item_count){
		$data = array('item_count' => $item_count);
		$condition = "knowledge_id=$knowledge_id";
		$row = DB::update('knowledge',$data,$condition);
		if($row>0) return 1;
		else return 0;
	}
	*/
	/**
	 * 根据ID设置知识权限
	 * @param int $knowledge_id		知识ID
	 * @param int $flag_item_add				0：所有人可添加	1：指定小组可以添加	2：只有主题创建者可以添加
	 * @param int $flag_item_add_group_id		如果是绑定到小组，这里是小组的ID
	 * @param int $flag_item_view				0：所有人可浏览和下载		1：指定小组可以浏览和下载		2：只有主题创建者可以浏览和下载
	 * @param int $flag_item_view_group_id		如果是绑定到小组，这里是小组的ID
	 * @return int	1：成功 0：失败
	 */
	public function set_flag($knowledge_id,$flag_item_add,$flag_item_add_group_id,$flag_item_view,$flag_item_view_group_id){
		$data = array('flag_item_add'=>$flag_item_add,'flag_item_add_group_id'=>$flag_item_add_group_id,'flag_item_view'=>$flag_item_view,
			'flag_item_view_group_id'=>$flag_item_view_group_id);
		$condition = "knowledge_id=$knowledge_id";
		$row = DB::update('knowledge',$data,$condition);
		if($row>0) return 1;
		else return 0;
	}
	
	/**
	 * 根据ID获取一条知识
	 * @param int $knowledge_id		知识ID
	 * @return	一维数组
	 */
	public function get_knowledge_by_knowledge_id($knowledge_id){
		$sql = "SELECT k.*,u.username FROM ".DB::table('knowledge')." as k, ".
				DB::table('user')." as u WHERE k.user_id=u.user_id AND k.knowledge_id=$knowledge_id";
		$row = DB::fetchOne($sql);
		if(count($row) == 0){
			return array();
		}
		$tag = DB::fetchOne('SELECT tags FROM '.DB::table('model').' WHERE type = "know" AND relate_id = '.$knowledge_id);
		$row['tags'] = $tag['tags'];
		return $row;
	}
	
	/**
	 * 根据ID获取其后面的知识（不包括当前ID所指记录）
	 * @param int $knowledge_id		知识ID
	 * @param int $count			获取数量
	 * @return 二维数组
	 */
	public function get_knowledges_by_pro_id($knowledge_id,$count){
		$sql = "SELECT k.*,u.username FROM ".DB::table('knowledge')." as k, ".
				DB::table('user')." as u WHERE k.user_id=u.user_id AND k.knowledge_id>$knowledge_id ORDER BY k.mktime DESC limit $count";
		$r = DB::fetchArray($sql);
		return $r;
	}
	
	/**
	 * 根据ID获取其后面的知识数量（不包括当前ID所指记录）
	 * @param int $knowledge_id		知识ID
	 * @return int	数量
	 */
	public function get_knowledges_count_by_pro_id($knowledge_id){
		$row = DB::fetchOne("SELECT count(*) as num FROM ".DB::table('knowledge')." WHERE knowledge_id>$knowledge_id");
		return $row['num'];
	}
	
	/**
	 * 分页获取知识
	 * @param int $pagesize		每页大小
	 * @param int $pagenum		页号
	 * @return 二维数组()
	 */
	public function get_knowledges($pagesize,$pagenum){
		if($pagesize<=0 || $pagenum<=0) return array();
		$row = DB::fetchOne("SELECT count(*) as num FROM ".DB::table('knowledge'));
		$totalcount = $row['num'];
		if($totalcount==0) return array();
		//分页获取
		$totalpage = ceil($totalcount / $pagesize);
		$pagenum = min($totalpage, $pagenum);
		$limitstart = ($pagenum-1)*$pagesize;
		$sql = "SELECT k.*,u.username FROM ".DB::table('knowledge')." as k, ".
				DB::table('user')." as u WHERE k.user_id=u.user_id ORDER BY k.mktime DESC limit $limitstart,$pagesize";
		$r = DB::fetchArray($sql);
		return $r;
	}
	/**
	 * 所有知识数量
	 * @return int 数量
	 */
	public function get_knowledges_count(){
		$row = DB::fetchOne("SELECT count(*) as num FROM ".DB::table('knowledge'));
		return $row['num'];
	}
	
	/**
	 * 根据用户ID分页获取其知识
	 * @param int $user_id		用户ID
	 * @param int $pagesize		每页大小
	 * @param int $pagenum		页号
	 * @return 二维数组
	 */
	public function get_knowledges_by_user_id($user_id,$pagesize,$pagenum){
		if($pagesize<=0 || $pagenum<=0) return array();
		$row = DB::fetchOne("SELECT count(*) as num FROM ".DB::table('knowledge')." WHERE user_id=$user_id ");
		$totalcount = $row['num'];
		if($totalcount==0) return array();
		//分页获取
		$totalpage = ceil($totalcount / $pagesize);
		$pagenum = min($totalpage, $pagenum);
		$limitstart = ($pagenum-1)*$pagesize;
		$r = DB::fetchArray("SELECT * FROM ".DB::table('knowledge')." WHERE user_id=$user_id ORDER BY mktime DESC limit $limitstart,$pagesize");
		return $r;
	}
	/**
	 * 根据用户ID获取其知识数量
	 * @param int $user_id		用户ID
	 * @return int 数量
	 */
	public function get_knowledges_count_by_user_id($user_id){
		$row = DB::fetchOne("SELECT count(*) as num FROM ".DB::table('knowledge')." WHERE user_id=$user_id ");
		return $row['num'];
	}
	
	/**
	 * 根据主题归档分页获取其知识
	 * @param int $main_tag		主题归档
	 * @param int $pagesize		每页大小
	 * @param int $pagenum		页号
	 * @return 二维数组
	 */
	public function get_knowledges_by_main_tag($main_tag,$pagesize,$pagenum){
		if($pagesize<=0 || $pagenum<=0) return array();
		$row = DB::fetchOne("SELECT count(*) as num FROM ".DB::table('knowledge')." WHERE main_tag='$main_tag' ");
		$totalcount = $row['num'];
		if($totalcount==0) return array();
		//分页获取
		$totalpage = ceil($totalcount / $pagesize);
		$pagenum = min($totalpage, $pagenum);
		$limitstart = ($pagenum-1)*$pagesize;
		$sql = "SELECT k.*,u.username FROM ".DB::table('knowledge')." as k, ".
				DB::table('user')." as u WHERE k.user_id=u.user_id AND main_tag='$main_tag' ORDER BY k.mktime DESC limit $limitstart,$pagesize";
		$r = DB::fetchArray($sql);
		return $r;
	}
	
	/**
	 * 根据主题归档获取其知识数量
	 * @param int $main_tag		主题归档
	 * @return int 数量
	 */
	public function get_knowledges_count_by_main_tag($main_tag){
		$row = DB::fetchOne("SELECT count(*) as num FROM ".DB::table('knowledge')." WHERE main_tag=$main_tag ");
		return $row['num'];
	}
	
	/**
	 * 根据关键词搜索（模糊匹配）知识
	 * @param string $keyword	关键词
	 */
	public function search_knowledges_by_keyword($keyword,$pagesize,$pagenum){
		if($pagesize<=0 || $pagenum<=0) return array();
		$sql = "SELECT count(*) as num FROM ".DB::table('knowledge')." as k, ".
				DB::table('user')." as u WHERE k.user_id=u.user_id AND (k.subject like '%$keyword%' OR k.message like '%$keyword%')";
		$row = DB::fetchOne($sql);
		$totalcount = $row['num'];
		if($totalcount==0) return array();
		//分页获取
		$totalpage = ceil($totalcount / $pagesize);
		$pagenum = min($totalpage, $pagenum);
		$limitstart = ($pagenum-1)*$pagesize;
		$sql = "SELECT k.*,u.username FROM ".DB::table('knowledge')." as k, ".
				DB::table('user')." as u WHERE k.user_id=u.user_id AND (k.subject like '%$keyword%' OR k.message like '%$keyword%') ORDER BY k.mktime DESC limit $limitstart,$pagesize";
		$r = DB::fetchArray($sql);
		return $r;
	}
	
	
	/****************************knowledge_item 部分*********************************/
	/**
	 * 增加一条 知识条目
	 * @param int $knowledge_id		所属知识ID
	 * @param int $user_id			用户（添加者）ID
	 * @param int $type				类型  0:message 1:file
	 * @param string $data			文件：序列化的信息	文字：直接是文字
	 * @return int 	0：失败    其他：新插入记录ID		
	 */
	public function add_knowledge_item($knowledge_id,$user_id,$type,$data){
		$data = array('knowledge_id' => $knowledge_id,'user_id' => $user_id,'type' => $type,'data' => $data,'mktime'=>time());
		$knowledge_item_id = DB::insert('knowledge_item', $data);
		//knowledge 表相应item_count+1,如果文件类型为1(file) atta_count+1;
		if($type==1){
			$sql = "UPDATE ".DB::table('knowledge')." SET item_count=item_count+1,atta_count=atta_count+1 WHERE knowledge_id=$knowledge_id";
		}else{
			$sql = "UPDATE ".DB::table('knowledge')." SET item_count=item_count+1 WHERE knowledge_id=$knowledge_id";
		}
		$r=DB::query($sql);
		if(!$r) return 0;
		else return $knowledge_item_id;
	}
	
	/**
	 * 根据条目ID 删除 知识条目
	 * @param int $knowledge_item_id		知识条目ID
	 * @return 1:成功 0：失败
	 */
	public function delete_knowledge_item($knowledge_item_id){
		$knowledge_item_row = DB::fetchOne("SELECT * FROM ".DB::table('knowledge_item')." WHERE knowledge_item_id = $knowledge_item_id");
		if(empty($knowledge_item_row)||count($knowledge_item_row)==0) return 0;
		$knowledge_id = $knowledge_item_row['knowledge_id'];
		$type = $knowledge_item_row['type'];
		$condition = "knowledge_item_id=$knowledge_item_id";
		$row = DB::delete('knowledge_item',$condition);
		//knowledge 表相应item_count-1 如果文件类型为1(file) atta_count-1;
		if($type==1){
			$sql = "UPDATE ".DB::table('knowledge')." SET item_count=item_count-1,atta_count=atta_count-1 WHERE knowledge_id=$knowledge_id";
		}else{
			$sql = "UPDATE ".DB::table('knowledge')." SET item_count=item_count-1 WHERE knowledge_id=$knowledge_id";
		}
		$r=DB::query($sql);
		if($row>0&&$r) return 1;
		else return 0;
	}
	
	/**
	 * 根据条目ID 修改 知识条目
	 * @param int $knowledge_item_id	知识条目ID
	 * @param int $knowledge_id			所属知识ID
	 * @param int $user_id				用户（添加者）ID
	 * @param int $type					类型  0:message 1:file
	 * @param string $data				文件：序列化的信息	文字：直接是文字
	 * @return 1:成功 0：失败
	 */
	public function modify_knowledge_item($knowledge_item_id,$knowledge_id,$user_id,$type,$data){
		$data = array('knowledge_id' => $knowledge_id,'user_id' => $user_id,'type' => $type,'data' => $data);
		$condition = "knowledge_item_id=$knowledge_item_id";
		$row = DB::update('knowledge_item',$data,$condition);
		if($row>0) return 1;
		else return 0;
	}
	
	/**
	 * 根据条目ID 获取一条条目
	 * @param int $knowledge_item_id	条目ID
	 * @return 一维数组
	 */
	public function get_knowledge_item_by_knowledge_item_id($knowledge_item_id){
		$row = DB::fetchOne("SELECT * FROM ".DB::table('knowledge_item')." WHERE knowledge_item_id = $knowledge_item_id");
		if(count($row) == 0){
			return array();
		}
		return $row;
	}
	
	/**
	 * 根据条目ID与知识ID获取其后面的知识条目（不包括当前ID所指记录）
	 * @param int $knowledge_item_id		条目ID
	 * @param int $knowledge_id				知识ID
	 * @param int $count					获取的数量
	 * @return 二维数组
	 */
	public function get_knowledge_items_by_pro_id($knowledge_item_id,$knowledge_id,$count){
		$r = DB::fetchArray("SELECT * FROM ".DB::table('knowledge_item')." WHERE knowledge_id=$knowledge_id AND knowledge_item_id>$knowledge_item_id ORDER BY mktime DESC limit $count");
		return $r;
	}
	/**
	 * 根据条目ID与知识ID获取其后面的知识条目数量（不包括当前ID所指记录）
	 * @param int $knowledge_item_id		条目ID
	 * @param int $knowledge_id				知识ID
	 * @return int 数量
	 */
	public function get_knowledge_items_count_by_pro_id($knowledge_item_id,$knowledge_id){
		$r = DB::fetchOne("SELECT count(*) as num FROM ".DB::table('knowledge_item')." WHERE knowledge_id=$knowledge_id AND knowledge_item_id>$knowledge_item_id");
		return $r['num'];
	}
	
	/**
	 * 根据知识ID分页获取知识条目
	 * @param int $knowledge_id		知识ID
	 * @param int $pagesize			每页大小
	 * @param int $pagenum			页号
	 * @return 二维数组
	 */
	public function get_knowledge_items_by_knowledge_id($knowledge_id,$pagesize,$pagenum){
		if($pagesize<=0 || $pagenum<=0) return array();
		$row = DB::fetchOne("SELECT count(*) as num FROM ".DB::table('knowledge_item')." WHERE knowledge_id=$knowledge_id ");
		$totalcount = $row['num'];
		if($totalcount==0) return array();
		//分页获取
		$totalpage = ceil($totalcount / $pagesize);
		$pagenum = min($totalpage, $pagenum);
		$limitstart = ($pagenum-1)*$pagesize;
		$r = DB::fetchArray("SELECT * FROM ".DB::table('knowledge_item')." WHERE knowledge_id=$knowledge_id ORDER BY mktime DESC limit $limitstart,$pagesize");
		return $r;
	}
	/**
	 * 根据知识ID获取知识条目数量
	 * @param int $knowledge_id		知识ID
	 * @return int 数量
	 */
	public function get_knowledge_items_count_by_knowledge_id($knowledge_id){
		$row = DB::fetchOne("SELECT count(*) as num FROM ".DB::table('knowledge_item')." WHERE knowledge_id=$knowledge_id ");
		return $row['num'];
	}
	
	public function save_file(&$data, $filename){
		$type = $this->get_type_by_file_name($filename);
		$local_name = md5(microtime()).$type;
		$dir = 'cache/attachment/'.$local_name;
		if(file_put_contents(ROOT.$dir, $data)){
			$data = '';
			unset($data);
			return '/'.$dir;
		}else{
			return '';
		}
	}
	function get_type_by_file_name($file_name){
		$start = strrpos($file_name, '.');
		if($start !== FALSE){
			return substr($file_name, $start);
		}
		return 'unknown';
	}
}

?>